import { LoginByAccount } from '../../api/login'
const permission = {
  state: {
    username: localStorage.getItem('loginInfo') ? localStorage.getItem('loginInfo').account : '',
    password: localStorage.getItem('loginInfo') ? localStorage.getItem('loginInfo').password : '',
    loginInfo: localStorage.getItem('loginInfo'),
    user: JSON.parse(localStorage.getItem('user')),
    newrouter: [],
    menutab: localStorage.getItem('menutab') ? Number.parseInt(localStorage.getItem('menutab')) : 3
  },
  mutations: {
    updateUsername (state, username) {
      state.username = username
    },
    updatePassword (state, password) {
      state.password = password
    },
    SET_LOGININFO: (state, params) => {
      state.loginInfo = params
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_NEWROUER: (state, newrouter) => {
      state.newrouter = newrouter
    },
    SET_MENUTAB: (state, menutab) => {
      state.menutab = menutab
    }
  },
  actions: {
    Logins ({ commit }, info) {
      return new Promise((resolve, reject) => {
        LoginByAccount(info).then(response => {
          const res = response.data
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      }).catch(error => {
        Promise.reject(error)
      })
    },
    saveStatus ({ commit }, newrouter) {
      return new Promise((resolve, reject) => {
        commit('SET_NEWROUER', newrouter) // 存储最新路由
        resolve(newrouter)
      }).catch(error => {
        Promise.reject(error)
      })
    },
    Logout ({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_USERNAME', '')
        commit('SET_STATUS', '')
        commit('SET_NEWROUER', [])
        commit('SET_USER', [])
        location.reload()
        sessionStorage.removeItem('USERNAME')
        sessionStorage.removeItem('STATUS')
        resolve()
      }).catch(error => {
        Promise.reject(error)
      })
    }
  }
}
export default permission
